package com.tuinui.trade.controller.job;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: kaweepapkongkittisan
 * Date: 5/25/13
 * Time: 5:43 PM
 * To change this template use File | Settings | File Templates.
 */


public class MailHandlerServlet extends HttpServlet {
    final public static Logger _log = LoggerFactory.getLogger(MailHandlerServlet.class);

    public void doPost(HttpServletRequest req,
                       HttpServletResponse resp)
            throws IOException {
        _log.debug("email coming...");
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        try{
            MimeMessage message = new MimeMessage(session, req.getInputStream());
            Multipart multipart = (Multipart)message.getContent();

            for(int i=0; i<message.getFrom().length; i++){
                _log.debug(message.getFrom()[i].toString());
            }
            long count = multipart.getCount();
            for(int i=0; i<count; i++){
                _log.debug("body" + i + " " + multipart.getBodyPart(i).getContent());
            }
        }catch(Exception e){
            throw new IOException("Cannot handle inbound email");
        }


    }
}